import axios from 'axios';
import router from '@/router/index-enhanced';
import { config } from '@/config';

// 创建 Axios 实例
const axiosInstance = axios.create({
    baseURL: config.API_BASE_URL,
    timeout: 10000
});

// 请求拦截器
axiosInstance.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('token');
        if (token) {
            config.headers.Authorization = `${token}`;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
axiosInstance.interceptors.response.use(
    (response) => {
        const { code, msg } = response.data;
        
        // 处理登录失效
        if (code === 410 || code === 401) {
            localStorage.removeItem('token');
            router.push('/login');
            return Promise.reject(new Error(msg || '登录已失效，请重新登录'));
        }
        
        return response;
    },
    (error) => {
        if (error.response) {
            if (error.response.status === 401) {
                localStorage.removeItem('token');
                router.push('/login');
            }
        }
        return Promise.reject(error);
    }
);

// 封装请求函数
const request = async (method, url, data = null) => {
    try {
        const config = {
            method,
            url,
        };
        
        // 根据请求方法决定数据放置位置
        if (method.toLowerCase() === 'get' && data) {
            config.params = data;
        } else if (data) {
            config.data = data;
        }
        
        const response = await axiosInstance(config);
        return response.data;
    } catch (error) {
        throw error
    }
};

export default request;
